<?php
namespace app\controller;

use think\Request;
use think\facade\Db;
use think\facade\Cache;

class Online extends Common
{

	/**
	 * 查询数据
	 *
	 * @return
	 */
	public function read(Request $request) {
		if($this->hasPermission($request->sessInfo, 'online:read')) {
			return ['code'=> 403, 'msg'=> '你没有权限执行此操作!'];;
		}
		$where = [];

		if( $request->sessInfo['level'] > 1 ) {
			array_push( $where, ['companyId', '=', $request->sessInfo['companyId'] ] );
		}

		$items = [];
		array_push( $where, ['type', '=', 1] );
		$query = Db::name('cfg_logs')->where($where)->whereTime('time','-7 day')->select()->toArray();
		$address = new \Net\IpLocation( app()->getRootPath() . 'data' . DIRECTORY_SEPARATOR . 'qqwry.dat');
		foreach($query as $value) {
			$online = Cache::get($value['cookie']);
			if($online) {
				$user = Db::table('cfg_user')->field('level, role')->where('username', $value['user'])->find();
				$value['department'] = Db::table('cfg_role')->where('id', isset($user['role']) ? $user['role'] : 0)->value('roleName');
				$value['ipName'] = $address->getAddrName($value['ip']);
				$level = isset($user['level']) ? $user['level'] : 3;
				$value['min'] = time() - $value['time'];
				if( $request->sessInfo['level'] == 1 ) {
					if( $level > 1 ) {
						array_push($items, $value );
					}
				} else {
					if($level == 3) {
						array_push($items, $value );
					}
				}
			}
		}
		return ['code'=> 0, 'msg'=> '', 'count'=> 0, 'data'=> $items ];
	}

	/**
	 * 强制清退
	 *
	 * @return
	 */
	public function offline(Request $request) {
		if($this->hasPermission($request->sessInfo, 'user:read')) {
			return ['code'=> 403, 'msg'=> '你没有权限执行此操作!'];;
		}
		$param = $request->param();
		if( !isset($param['id']) ) {
			return ['code'=> 403, 'msg'=> '操作失败!'];
		}
		$explode = explode(',', $param['id']);
		foreach( $explode as $value ) {
			$cookie = Db::table('cfg_logs')->where('id', $value)->value('cookie');
			if($cookie) {
				Cache::delete($cookie);
			}
		}
		return ['code'=> 0, 'msg'=> '用户清退成功!'];
	}

}
